<?php
namespace Home\Controller;

use Home\Model\StorageDetailModel;
use Home\Model\OfficeStationeryModel;
use Home\Model\InventoryInformationModel;
use Think\Model\RelationModel;
use Home\Model\ApplicationFormModel;

class StorageDetailController extends CommonController{
	
	protected $table="storage_detail";
  protected $pageSize = 12;

  public function index(){
  	$getalldepartments_url = "Department/getAllDepartments";
    $alldepartments = json_decode(http_get($getalldepartments_url),true);
	$this->assign('belongsDepartment',D('ApplicationForm')->getSelfDepartments());
	$this->assign('departName',D('ApplicationForm')->getSelfDepartment());
  	$this->display();
  }


	public function getList(){
	$this->setQeuryCondition();
    $count = (int)$this->M->count();
    $this->setQeuryCondition();
    $list = $this->M->page(I('get.p',0). ','. $this->pageSize)->order('id desc')->select();
    
	foreach ($list as $k => $v) {
      $list[$k]['type']=M('office_stationery')->where(array('name'=>$v['name'],'specification'=>$v['specification'],'unit'=>$v['unit']))->getField('type');
    }
	foreach ($list as $k => $v) {
	  $list[$k]['sum'] = $list[$k]['price'] *  $list[$k]['num'];
	  $list[$k]['sum'] = sprintf("%.2f", $list[$k]['sum']);
    }
	
    $result = array('list'=>$list, 'count'=>$count);
		$this->ajaxReturn($result);

	}

 	//设置查询
  public function setQeuryCondition(){
  	if (isset($_GET['belongs_department'])) {
		$this->M->where(array("belongs_department"=> array('EQ', I('get.belongs_department'))));
	}else{
		$this->M->where(array("belongs_department"=> array('EQ', D('ApplicationForm')->getSelfDepartment())));
	}

	if (I('get.name')) {
		$this->M->where(array("name"=> array('like', "%".I('get.name')."%")));
	}
	
	if (I('get.start1') && I('get.start2')) {
		$start1 = I('get.start1');
		$start2 = I('get.start2');
		$d = date('Y-m-d',strtotime($start2)+86400);
		$this->M->where(array("order_time"=> array('between', "$start1,$d")));
	}
		
    $this->M->where( array('info_status'=>array('EQ', 1) ) );

  }

	
	
    /**
	 * 新增
	 */
    public function add(){
    	
    	$_POST['app_name']=$_SESSION['account']['userInfo']['user_id'];
		$_POST['belongs_department'] = D('ApplicationForm')->getSelfDepartment();
    	$re = $this->M->create($_POST, 1);
		
    	if($re){
    		$this->M->startTrans(); //开启事务
    		
    		//构造插入库存数据表的数据
    		$result = array();
			$result['name'] = $re['name'];
			$result['unit'] = $re['unit'];
			$result['specification'] = $re['specification'];
			$result['belongs_department'] = $re['belongs_department'];
			//查询用品资料表，获取类型，价格等数据
			$res = D('officeStationery')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification']))->select();
			if(!$res){
				$this->M->rollback();
				$this->error($this->M->getError());
			}else{
				$result['type'] = $res[0]['type'];
			    $result['price']= $res[0]['price'];
			}
			
			//查询当前库存表是否已经存在该用品
			$relt = D('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>$result['belongs_department']))->select();
			if($relt){
				$result['total_num'] = $relt[0]['total_num'] + $re['num'];
			    $result['inventory_num'] = $relt[0]['inventory_num'] + $re['num'];
				
				if (M('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>$result['belongs_department']))->save($result) !== false) {
					$this->M -> add();
					$this->M->commit();
					$this->success(L('ADD_SUCCESS'));
				} else {
					$this->M->rollback();
					$this->error($this->M->getError().$this->M->getLastSql());
				}
				
			}else{
				$result['total_num'] =  $re['num'];
			    $result['inventory_num'] =  $re['num'];
				if(D('inventoryInformation')->relation(true)->add($result)!== false){
				    $this->M -> add();
					$this->M->commit();
					$this->success(L('ADD_SUCCESS'));
				}else {
					$this->M->rollback();
					$this->error($this->M->getError().$this->M->getLastSql());
				}
			}
			
			
    	}else{
    		$this->error($this->M->getError());
    	}
    }




    /**
	 * 删除
	 */
    public function delete(){
    	$id = I("post.ids");
		if(!$id){
			$this->error(L('DELETE_ERROR').$this->M->getError());
		}else{
			$this->M->startTrans(); //开启事务
			if($this->M->data(array('info_status'=>-1))->where(array('id'=>array('in', $id)))->save()){
				//查询删除的数据 相关信息
				$result = array();
				$re = D('storage_detail')->where(array('id'=>array('in', $id)))->select();
				$result['name'] = $re[0]['name'];
				$result['unit'] = $re[0]['unit'];
				$result['specification'] = $re[0]['specification'];
				$res = D('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->select();
				
				if(!$res){
					$this->M->rollback();
					$this->error($this->M->getError().$this->M->getLastSql());
				}else{
					$result['total_num'] = $res[0]['total_num'] - $re[0]['num'];
				    $result['inventory_num'] = $res[0]['inventory_num'] - $re[0]['num'];
					if($result['inventory_num']<0){
						$this->M->rollback();
						$this->error('若删除，该用品库存不足');
					}else{
						if (M('inventoryInformation')->where(array('name'=>$result['name'],'unit'=>$result['unit'],'specification'=>$result['specification'],'belongs_department'=>D('ApplicationForm')->getSelfDepartment()))->save($result) !== false) {
							$this->M->commit();
							$this->success(L('ADD_SUCCESS'));
						} else {
							$this->M->rollback();
							$this->error($this->M->getError().$this->M->getLastSql());
						}
					}
					
				}
			}
		}
    }













}